<?php
/**
*+-------IMBA赛事下的赛程业务数据的获取操作--------+
*+-------------------------------------------------+
*+--------------基于MongoDB存储的------------------+
*+-------------------------------------------------+
*+-@author susy.liang <liangling@ilongyuan.com.cn>-+
*+-------------------------------------------------+
*/
namespace Api\Event;

use Api\Constract\IPosable;

class RaceGroupEvent extends BaseEvent implements IPosable {

	/**
	*模型对象
	*/
	protected $mod;

	/**
	*成员变量的初始化
	*/
	protected function _initialize(){
		parent::_initialize();
		$this->mod = D('Common/RaceGroup', 'Service');
	}
    
    /**
    *比赛列表数据
    *@param null
    *@return array
    */
    public function lists($query = '', $field='', $limit=0, $p=0, $orderby='sort asc'){
    	$map = array('status'=>array('gt', 0),);
    	$query && $map = array_merge($map, $query);

    	$res = $this->mod->where($map)->field($field)->order($orderby);
    	if($limit)
    		$res = $res->limit($limit);
    	if($p)
    		$res = $res->page($p);

    	return $res->select();
    }

    /** 
	 * 取总赛程数
	 * @author susy<susy.liang@ilongyuan.com.cn>
	 */
	
	public function total()
	{

		$map = array('status'=>array('gt', 0));

		return $this->mod->where($map)->count();
	}


    /** 
     * 获取展示的赛程列表
     * @param 
     * @return 
     */
    
    public function showLists()
    {
    	$map = array('status'=>array('gt', 0),);
    	return $this->mod->where($map)->select();
    }

    /**
	*比赛的具体明细信息
	*@param int $id 比赛标识
	*@param bool $moreDetail 是否获取更详细信息 默认不获取
	*@return array 明细数据
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function info($id=0, $defLogo='')
	{
		$data = self::$STATIC['raceGroup'][$id];
		if(!$data){
			$servObj = D('Common/RaceGroup', 'Service');
			$map = array();
			$map['status'] = array('egt', 0);
			$map['id']     = intval($id);
			$data = $servObj->where($map)->find();
			unset($data['_id']);
			
			$match = A('Api/Match', 'Event')->info(intval($data['match_id']));
			if(!$defLogo){
				$defLogo = $match['teamlogo'];
				uri_format($defLogo);
			}
			$data['match'] = $match;
			
			$game = A('Api/Game', 'Event')->info(intval($data['game_id']));
			uri_format($game['logo']);
			$data['game'] = $game;

			$team = array();
			if($data['competitor']){
				$teamObj = A('Api/Team', 'Event');
				foreach ($data['competitor'] as $key => $value) {//id,full_name as name,name as shortName
					$res = $teamObj->infoByName($value, 'id,full_name,name,logo');

					$team[] = array(
							'id'=>$res['id'],
							'name'=>$res['full_name']?$res['full_name']:$value,
							'shortName'=>$res['name']?$res['name']:$value,
							'logo'=>$res['logo']?$res['logo']:$defLogo
						);
				}
			}
			$data['team'] = $team;

			$recVideo = $this->recommendVideo($data['race_ids'], $data['video_ids']);
			$data['list'] = $recVideo?$recVideo:array();

			self::$STATIC['raceGroup'][$id] = $data;
		}
		

		return $data;
	}

	/**
	*获取比赛的视频推荐
	*@param int $raceId 比赛组的标识
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	private function recommendVideo($raceIds=array(), $videoIds=array()){
		if(empty($raceIds) || empty($videoIds))
			return false;

		$serVideo = D('Common/Video', 'Service');
		$vmap = array(
					'id'=>array('in', $videoIds),
					'type'=>$serVideo::TYPE_NORMAL,
					'status'=>$serVideo::STATUS_PASS
				);
		$videos = $serVideo->where($vmap)->field('id,title')->select();
		$temp = array();
		foreach ($videos as $key => $value) {
			unset($value['_id']);
			$temp[$value['id']] = $value;
		}
		$videos = $temp;

		$rmap = array(
					'id'=>array('in', $raceIds),
					'type'=>$serVideo::TYPE_MATCH,
					'status'=>$serVideo::STATUS_PASS
					);
		$races = $serVideo->where($rmap)->field('id,title,round')->select();
		$temp = array();
		foreach ($races as $key => $value) {
			unset($value['_id']);
			$temp[$value['id']] = $value;
		}
		$races = $temp;

		$data = array();
		foreach ($videoIds as $key => $value) {
			if($videos[$value]){
				$raceId = $raceIds[$key];
				$data[] = array(
							'id'=>$raceId,
							'video_id'=>$value,
							'title'=>$videos[$value]['title'],
							'round'=>$races[$raceId]['round']
					);
			}
			
		}

		return $data;
	}



	/** 
	 * 比赛订阅数的设置 加减1
	 * @param $raceId int 比赛标识
	 * @param $plus boolean 增减 默认加1
	 * @return boolean
	 * @author susy.liang<liangling@ilongyuan.com.cn>
	 */	
	public function scribe($raceId, $plus = true)
	{
		$where = array('id'=>intval($raceId));
		$act = $plus ? 'setInc' : 'setDec';
		return $this->mod->where($where)->$act('scribe', 1);
	}

	/**
	*获取比赛的各局比赛信息
	*@param $raceId int 比赛ID
	*@param $detail boolean 明细 默认不获取
	*/
	public function sigleRace($raceId, $field='id,title,round', $detail=false, $limit=0){

		$servObj = D('Common/Video', 'Service');
		$map = array(
				'group_id'=>intval($raceId),
				'status'=>$servObj::STATUS_PASS
			);
		$res = $servObj->where($map)->field($field);
		$limit && $res=$res->limit($limit);
		$res = $res->select();

		$data = array();
		if($detail===true){

		}else{
			foreach ($res as $key => $value) {
				unset($value['_id']);
				array_push($data, $value);
			}
		}
		return $data;
	}

	
	/**
	*直播比赛
	*/
	public function live(){

	}

	/**
	*比赛日期分组
	*@param $id int 赛事标识
	*@param $p int 返回的键值组
	*@param $limit int 组的length
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function raceTimeGroup($id, $p=1, $limit=5){
		$dates = self::$STATIC['raceTimeGroup'][$id];
		if(!$dates){
			$dates = $this->mod->where(array('match_id'=>intval($id), 'state'=>1))
					->order('race_date desc')->getField('race_date', true);
			$dates = array_unique($dates);

			$dates = array_chunk($dates, $limit);
			self::$STATIC['raceTimeGroup'][$id] = $dates;
		}

		if($p > count($dates))
			return false;
		else	
			return $dates[$p-1];
	}

	/**
	*获取比赛的相关比赛推荐
	*取同一赛事下的任3条比赛
	*@author susy.liang<liangling@ilongyuan.com.cn> 
	*/
	public function getReferRace($matchId=0, $raceId=0, $limit=3){

		//$eventObj = A('Api/RaceGroup', 'Event');
		$map = array(
				'match_id'=>intval($matchId),
				'status'=>1,
				//'state'=>1,
			);
		$total = $this->mod->where($map)->count();
		if($total){
			$random = rand(0, $total-$limit);
			$map['id'] = array('neq', intval($raceId));
			$ids = $this->mod->where($map)->field('id')->limit($random, $limit)->order('race_time desc')->select();

			$items = array();
			foreach ($ids as $key => $value) {
				$detail = $this->info($value['id']);
				$items[] = $detail;
			}

		}
		return $items;
	}

	/**
	 * 格式化比赛
	 * 网站用
	 * @author liubo <liubo@ilongyuan.com.cn>
	 */
	public function format_races($ids = [], $groupByDate = true) {
        $data = [];
        if(empty($ids)) return $data;
        $fieldMap = ['id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'game', 'match', 'cover'];
        $rgEvent = event('RaceGroup');
        $vEvent = event('Video');
        foreach ($ids as $key => $value) {
            $detail = $rgEvent->info($value);
            $detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):[];
            $detail['game'] = field_filter($detail['game'], ['id','name','logo']);
            $detail['match'] = field_filter($detail['match'], ['id','title','cover','pc_cover']);
            $races = $vEvent->lists(['group_id' => $detail['id'], 'type' => 1], 0, true);
            if (!empty($races) && is_array($races)) {
                sort($races);
                $races = array_slice($races, 0, 4);
            }
            $detail = field_filter($detail, $fieldMap);
            $detail['races'] = $races;
            $race[$detail['race_date']][] = $detail;
        }

        foreach ($race as $key => $value) {
            foreach ($value as $k => &$v) {
                uri_format($v['cover']);
                uri_format($v['match']['cover']);
                uri_format($v['match']['pc_cover']);
                if (empty($v['match']['pc_cover'])) {
                    $v['match']['pc_cover'] = $v['match']['cover'];
                }
            }
            if ($groupByDate) {
                $data[] = ['date'=>$key, 'list'=>$value];
            } else {
                $data = array_merge($data, $value);
            }
        }
        return $data;
    }
}